// DOM元素获取
const menuToggle = document.getElementById('menuToggle');
const sidebar = document.querySelector('.sidebar');
const mainContent = document.querySelector('.main-content');
const notificationsBtn = document.getElementById('notificationsBtn');
const notificationsSidebar = document.getElementById('notificationsSidebar');
const closeNotificationsSidebar = document.getElementById('closeNotificationsSidebar');
const sidebarOverlay = document.getElementById('sidebarOverlay');
const markAllReadBtn = document.querySelector('.mark-all-read');
const themeBtns = document.querySelectorAll('.theme-btn');
const saveSettingsBtn = document.querySelector('.save-settings-btn');
const refreshIntervalSelect = document.getElementById('refreshInterval');
const showStatsCheckbox = document.getElementById('showStats');
const showChartsCheckbox = document.getElementById('showCharts');
const showActivityCheckbox = document.getElementById('showActivity');

// 侧边栏切换功能
function initSidebarToggle() {
    menuToggle.addEventListener('click', () => {
        sidebar.classList.toggle('collapsed');
        mainContent.classList.toggle('expanded');
        sidebarOverlay.classList.toggle('visible');
        document.body.style.overflow = sidebarOverlay.classList.contains('visible') ? 'hidden' : '';
    });

    sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.add('collapsed');
        mainContent.classList.add('expanded');
        sidebarOverlay.classList.remove('visible');
        document.body.style.overflow = '';
    });
}

// 通知侧边栏功能
function initNotificationsSidebar() {
    notificationsBtn.addEventListener('click', () => {
        notificationsSidebar.classList.add('open');
        sidebarOverlay.classList.add('visible');
        document.body.style.overflow = 'hidden';
    });

    closeNotificationsSidebar.addEventListener('click', closeNotifications);
    sidebarOverlay.addEventListener('click', (e) => {
        if (!sidebar.contains(e.target)) {
            closeNotifications();
        }
    });

    function closeNotifications() {
        notificationsSidebar.classList.remove('open');
        sidebarOverlay.classList.remove('visible');
        document.body.style.overflow = '';
    }

    // 全部标为已读
    markAllReadBtn.addEventListener('click', () => {
        const unreadItems = document.querySelectorAll('.notification-item.unread');
        unreadItems.forEach(item => {
            item.classList.remove('unread');
            const dot = item.querySelector('.notification-dot');
            if (dot) dot.remove();
        });
    });
}

// 初始化销售趋势图表
function initSalesChart() {
    const ctx = document.getElementById('salesChart').getContext('2d');
    
    // 模拟数据
    const labels = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    const salesData = [1200, 1900, 1500, 2800, 2200, 3100, 3600, 3400, 4000, 4200, 4800, 5200];
    const targetData = [1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000];
    
    const chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '实际销售额',
                    data: salesData,
                    borderColor: '#3498db',
                    backgroundColor: 'rgba(52, 152, 219, 0.1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true
                },
                {
                    label: '目标销售额',
                    data: targetData,
                    borderColor: '#e74c3c',
                    backgroundColor: 'transparent',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    tension: 0.3,
                    fill: false
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        boxWidth: 6
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: '#3498db',
                    borderWidth: 1
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return '¥' + value.toLocaleString();
                        }
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'index'
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
    
    return chart;
}

// 初始化用户分布图表
function initUserDistributionChart() {
    const ctx = document.getElementById('userDistributionChart').getContext('2d');
    
    // 模拟数据
    const labels = ['华东', '华北', '华南', '西南', '西北', '东北'];
    const data = [25, 20, 15, 12, 18, 10];
    const colors = [
        'rgba(52, 152, 219, 0.8)',
        'rgba(155, 89, 182, 0.8)',
        'rgba(46, 204, 113, 0.8)',
        'rgba(231, 76, 60, 0.8)',
        'rgba(243, 156, 18, 0.8)',
        'rgba(26, 188, 156, 0.8)'
    ];
    
    const chart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: colors,
                borderColor: '#fff',
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    labels: {
                        padding: 20,
                        usePointStyle: true,
                        boxWidth: 6
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = Math.round((value / total) * 100);
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                }
            },
            animation: {
                animateScale: true,
                animateRotate: true,
                duration: 1000,
                easing: 'easeOutQuart'
            },
            cutout: '60%'
        }
    });
    
    return chart;
}

// 图表周期切换功能
function initChartPeriodToggle() {
    const periodBtns = document.querySelectorAll('.chart-period-btn');
    periodBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除所有按钮的活动状态
            periodBtns.forEach(b => b.classList.remove('active'));
            // 添加当前按钮的活动状态
            btn.classList.add('active');
            
            // 这里可以根据选择的周期更新图表数据
            // 简化处理，实际项目中应该有数据切换逻辑
            console.log('切换图表周期:', btn.textContent);
        });
    });
}

// 主题切换功能
function initThemeToggle() {
    themeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除所有按钮的活动状态
            themeBtns.forEach(b => b.classList.remove('active'));
            // 添加当前按钮的活动状态
            btn.classList.add('active');
            
            // 这里可以实现实际的主题切换逻辑
            const theme = btn.getAttribute('data-theme');
            console.log('切换主题:', theme);
            
            // 保存主题设置到本地存储
            localStorage.setItem('dashboardTheme', theme);
        });
    });
}

// 设置保存功能
function initSettingsSave() {
    saveSettingsBtn.addEventListener('click', () => {
        // 收集设置
        const settings = {
            refreshInterval: refreshIntervalSelect.value,
            showStats: showStatsCheckbox.checked,
            showCharts: showChartsCheckbox.checked,
            showActivity: showActivityCheckbox.checked,
            theme: document.querySelector('.theme-btn.active').getAttribute('data-theme')
        };
        
        // 保存到本地存储
        localStorage.setItem('dashboardSettings', JSON.stringify(settings));
        
        // 显示保存成功提示
        showNotification('设置已保存');
        
        // 应用设置
        applySettings(settings);
    });
}

// 应用设置
function applySettings(settings) {
    // 应用刷新间隔设置
    if (settings.refreshInterval && settings.refreshInterval > 0) {
        // 清除现有的定时器
        if (window.refreshTimer) {
            clearInterval(window.refreshTimer);
        }
        
        // 设置新的定时器
        window.refreshTimer = setInterval(() => {
            refreshDashboardData();
        }, settings.refreshInterval * 1000);
    } else if (window.refreshTimer) {
        clearInterval(window.refreshTimer);
    }
    
    // 应用显示选项设置
    const statsGrid = document.querySelector('.stats-grid');
    const chartsSection = document.querySelector('.charts-section');
    const activityCard = document.querySelector('.activity-card');
    
    if (statsGrid) statsGrid.style.display = settings.showStats ? 'grid' : 'none';
    if (chartsSection) chartsSection.style.display = settings.showCharts ? 'grid' : 'none';
    if (activityCard) activityCard.style.display = settings.showActivity ? 'block' : 'none';
}

// 加载保存的设置
function loadSettings() {
    const savedSettings = localStorage.getItem('dashboardSettings');
    if (savedSettings) {
        try {
            const settings = JSON.parse(savedSettings);
            
            // 恢复设置表单
            refreshIntervalSelect.value = settings.refreshInterval || '60';
            showStatsCheckbox.checked = settings.showStats !== false;
            showChartsCheckbox.checked = settings.showCharts !== false;
            showActivityCheckbox.checked = settings.showActivity !== false;
            
            // 恢复主题选择
            themeBtns.forEach(btn => {
                if (btn.getAttribute('data-theme') === settings.theme) {
                    btn.click();
                }
            });
            
            // 应用设置
            applySettings(settings);
        } catch (e) {
            console.error('加载设置失败:', e);
        }
    }
}

// 刷新仪表盘数据
function refreshDashboardData() {
    console.log('刷新仪表盘数据...');
    
    // 模拟数据更新
    updateRandomStats();
    
    // 可以在这里添加更多数据更新逻辑
}

// 更新随机统计数据
function updateRandomStats() {
    const statValues = document.querySelectorAll('.stat-value');
    const statChanges = document.querySelectorAll('.stat-change');
    
    statValues.forEach((valueElement, index) => {
        let currentValue = valueElement.textContent;
        
        // 处理数字格式
        if (currentValue.startsWith('¥')) {
            const numValue = parseFloat(currentValue.replace(/[^\d.]/g, ''));
            const change = numValue * (Math.random() * 0.02 - 0.01); // -1% to +1%
            const newValue = numValue + change;
            valueElement.textContent = '¥' + newValue.toLocaleString(undefined, {maximumFractionDigits: 0});
            
            // 更新变化指示器
            const changeText = document.createElement('span');
            changeText.className = change >= 0 ? 'stat-change positive' : 'stat-change negative';
            changeText.textContent = (change >= 0 ? '+' : '') + (change / numValue * 100).toFixed(1) + '%';
            
            if (statChanges[index]) {
                statChanges[index].replaceWith(changeText);
            }
        } else if (currentValue.endsWith('%')) {
            const numValue = parseFloat(currentValue);
            const change = (Math.random() * 0.2 - 0.1); // -0.1% to +0.1%
            const newValue = numValue + change;
            valueElement.textContent = newValue.toFixed(1) + '%';
            
            // 更新变化指示器
            const changeText = document.createElement('span');
            changeText.className = change >= 0 ? 'stat-change positive' : 'stat-change negative';
            changeText.textContent = (change >= 0 ? '+' : '') + change.toFixed(1) + '%';
            
            if (statChanges[index]) {
                statChanges[index].replaceWith(changeText);
            }
        } else {
            const numValue = parseInt(currentValue.replace(/[^\d]/g, ''));
            const change = Math.floor(numValue * (Math.random() * 0.02 - 0.01)); // -1% to +1%
            const newValue = numValue + change;
            valueElement.textContent = newValue.toLocaleString();
            
            // 更新变化指示器
            const changeText = document.createElement('span');
            changeText.className = change >= 0 ? 'stat-change positive' : 'stat-change negative';
            changeText.textContent = (change >= 0 ? '+' : '') + (change / numValue * 100).toFixed(1) + '%';
            
            if (statChanges[index]) {
                statChanges[index].replaceWith(changeText);
            }
        }
    });
}

// 显示通知
function showNotification(message, type = 'success') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    // 设置样式
    Object.assign(notification.style, {
        position: 'fixed',
        top: '20px',
        right: '-400px',
        background: type === 'success' ? '#2ecc71' : '#e74c3c',
        color: 'white',
        padding: '15px 30px',
        borderRadius: '5px',
        boxShadow: '0 4px 10px rgba(0, 0, 0, 0.1)',
        zIndex: '9999',
        transition: 'right 0.3s ease'
    });
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.right = '20px';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.right = '-400px';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

// 初始化函数
function init() {
    initSidebarToggle();
    initNotificationsSidebar();
    initSalesChart();
    initUserDistributionChart();
    initChartPeriodToggle();
    initThemeToggle();
    initSettingsSave();
    loadSettings();
    
    // 初始化时刷新一次数据
    refreshDashboardData();
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);